package net.mikoo.seals.manage.web.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.concurrent.ExecutionException;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gson.WeChat;
import com.gson.bean.InMessage;
import com.gson.bean.UserInfo;
import com.gson.inf.EventTypes;
import com.gson.util.HttpKit;
import com.gson.util.Tools;
import com.gson.util.XStreamFactory;
import com.thoughtworks.xstream.XStream;

import net.mikoo.seals.biz.service.WechatService;
import net.mikoo.seals.common.WebContext;
import net.mikoo.seals.model.WechatUser;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


@Controller
@RequestMapping("/wechat")
public class WechatController{
	
	private  Logger logger = LoggerFactory.getLogger(WechatController.class);

	@Autowired
	public RedisTemplate<String, String> redisTemplate;
	
	@Autowired
	private WechatService wechatService;
	
	@RequestMapping("/access")
	public void access(HttpServletRequest request, HttpServletResponse response, Model model) {

		String method = request.getMethod();
		if (method.equals("GET")) {
			try {

				String path = request.getServletPath();
				String pathInfo = path.substring(path.lastIndexOf("/"));
				String _token="sjwl2015sjentqwoo";
				String outPut = "error";
				if (pathInfo != null) {
					_token = pathInfo.substring(1);
					String signature = request.getParameter("signature");// 微信加密签名
					String timestamp = request.getParameter("timestamp");// 时间戳
					String nonce = request.getParameter("nonce");// 随机数
					String echostr = request.getParameter("echostr");//
					// 验证
					if (WeChat.checkSignature(_token, signature, timestamp, nonce)) {
						outPut = echostr;
					}
					outPut = echostr;
				}
				response.getWriter().write(outPut);

			} catch (IOException e) {
				logger.error("访问微信出错！", e);
			}

		} else {

			try {
				response.setCharacterEncoding("UTF-8");
				response.setContentType("text/xml");
				ServletInputStream in = request.getInputStream();
				String xmlMsg = Tools.inputStream2String(in);
				logger.info("输入消息:[" + xmlMsg + "]");
				processing(xmlMsg);
				//String xml = WeChat.processing(xmlMsg);
				//response.getWriter().write(xml);

			} catch (Exception e) {
				logger.error("访问微信出错！", e);
			}
		}
	}
	
	/**
	 * 
	 * @param xmlMsg
	 * @throws Exception 
	 */
	public void processing(String xmlMsg) throws Exception {
		try {
			//转换微信post过来的xml内容
	        XStream xs = XStreamFactory.init(false);
	        xs.ignoreUnknownElements();
	        xs.alias("xml", InMessage.class);
	        InMessage msg = (InMessage) xs.fromXML(xmlMsg);
			if(msg.isEvent()) {
				System.out.println(msg.getEvent());
				if(msg.getEvent().equals(EventTypes.SUBSCRIBE.getType())) {
					
					String accessToken = redisTemplate.opsForValue().get(WebContext.WECHAT_ACCESS_TOKEN);
					String openid = msg.getFromUserName();
					
					UserInfo userinfo = WeChat.user.getUserInfo(accessToken, openid);
					if(userinfo != null) {
						WechatUser user = wechatService.getUserInfoByOpenId(openid);
						if(user == null) {
							user = new WechatUser();
							user.setOpenid(openid);
							user.setSubscribe(userinfo.getSubscribe());
							user.setNickname(userinfo.getNickname());
							user.setLanguage(userinfo.getLanguage());
							user.setCity(userinfo.getCity());
							user.setProvince(userinfo.getProvince());
							user.setCountry(userinfo.getCountry());
							user.setHeadimgurl(userinfo.getHeadimgurl());
							user.setUnionid(userinfo.getUnionid());
							wechatService.save(user);
						}
						
					}
				}
				
				if(msg.getEvent().equals(EventTypes.CLICK.getType())) {
					
					String accessToken = redisTemplate.opsForValue().get(WebContext.WECHAT_ACCESS_TOKEN);
					String openid = msg.getFromUserName();
					
					
					JSONObject mpnews = new JSONObject();
					mpnews.put("media_id", msg.getEventKey());
					
					JSONObject params = new JSONObject();
					params.put("touser", openid);
					params.put("mpnews", mpnews);
					params.put("msgtype", "mpnews");
					System.out.println(params.toString());
					
					String a = HttpKit.post("https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token="+accessToken,params.toString());

					System.out.println(a);
				}
				
			}
		}catch (Exception e) {
			logger.error("",e);
		}
		
	}
	
	
	
//	public ArrayList<Articles> getArticles() throws IOException{
//		String domain = ConfKit.get("domain");
//		String weixinAppDomain = ConfKit.get("weixin.app.domain");
//		weixinAppDomain += "index.php/Home/Index/Index/redirect_page/";
//		String appId = ConfKit.get("AppId");
//		Articles article1 = new Articles();
//		article1.setTitle("邀请好友拿现金");
//		article1.setDescription("邀请好友拿现金");
//		article1.setUrl(WeiXinApi.getOAuthUrl(weixinAppDomain + "haohan", appId));
//		article1.setPicUrl(domain + "assets/images/banner_pic10_900X500.png");
//		
//		Articles article2 = new Articles();
//		article2.setTitle("签到送红包，每天等你来");
//		article2.setDescription("签到送红包，每天等你来");
//		article2.setUrl(WeiXinApi.getOAuthUrl(weixinAppDomain + "sign", appId));
//		article2.setPicUrl(domain + "assets/images/banner_pic4_50X50.jpg");
//		
//		Articles article3 = new Articles();
//		article3.setTitle("招人啦！天马集结令，等的就是你");
//		article3.setDescription("招人啦！天马集结令，等的就是你");
//		article3.setUrl("http://mp.weixin.qq.com/s?__biz=MjM5NTI3MjQ1Nw==&mid=204678195&idx=2&sn=d34f2d0b5f753b3933704fe3a837d21c#rd");
//		article3.setPicUrl(domain + "assets/images/banner_pic2_50X50.jpg");
//		
//		Articles article4 = new Articles();
//		article4.setTitle("投资随机送红包");
//		article4.setDescription("投资随机送红包");
//		article4.setUrl(WeiXinApi.getOAuthUrl(weixinAppDomain + "random", appId));
//		article4.setPicUrl(domain + "assets/images/banner_pic5_50X50.jpg");
//		
//		Articles article5 = new Articles();
//		article5.setTitle("新用户注册，立送30元现金红包!");
//		article5.setDescription("新用户注册，送30元大红包!");
//		article5.setUrl(WeiXinApi.getOAuthUrl(weixinAppDomain + "reg", appId));
//		article5.setPicUrl(domain + "assets/images/hongbao.png");
//		
//		ArrayList<Articles> list = new ArrayList<Articles>();
//		list.add(article1);
//		list.add(article2);
//		list.add(article3);
//		list.add(article4);
//		list.add(article5);
//		return list;
//		
//		
//	}
	
	
	/**
	 * 
	 * @Description 微信刷新 access token
	 *
	 * @Version 1.0
	 *
	 * @Author huangxiaoming
	 *
	 * @Email huangxm129@163.com
	 *
	 * @History
	 *
	 *<li>Author: huangxiaoming</li>
	 *<li>Date: 2015年4月22日</li>
	 *<li>Version: 1.0</li>
	 *<li>Content: create</li>
	 *
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("/refreshAccessToken")
	public HttpEntity<String> refreshAccessToken(HttpServletRequest request, HttpServletResponse response,
			Model model) {
		JSONObject json = new JSONObject();
		try {
			String _token = WeChat.getAccessToken();
			logger.info(_token);
			System.out.println(_token);
			com.alibaba.fastjson.JSONObject resultTicketJson = WeChat.getTicket(_token);
			String ticket = resultTicketJson.getString("ticket");
			logger.info(ticket);
			redisTemplate.opsForValue().set(WebContext.WECHAT_ACCESS_TOKEN, _token);
			redisTemplate.opsForValue().set(WebContext.WECHAT_TICKET, ticket);
			json.put("code", "1");
			json.put("message", "刷新token成功！");
			return new ResponseEntity<String>(json.toString(),HttpStatus.OK);
		} catch (Exception e) {
			logger.error("",e);
			json.put("code", "-1");
			json.put("message", "刷新token系统错误");
			return new ResponseEntity<String>(json.toString(),HttpStatus.INTERNAL_SERVER_ERROR);
		}	
	}
	
//	@RequestMapping("/getRedisValue")
//	@ResponseBody
//	public void getRedisValue(HttpServletRequest request, HttpServletResponse response, Model model) {
//		String key = request.getParameter("key");
//		if(StringUtil.isBlank(key)) {
//			ValueOperations<String, String> cache = redisTemplate.opsForValue();
//			String accesToken = (String) cache.get(CacheConstants.WECHAT_ACCESS_TOKEN);
//			try {
//				response.getWriter().print(accesToken);
//			} catch (IOException e) {
//				logger.error("",e);
//			}
//		} else {
//			ValueOperations<String, String> cache = redisTemplate.opsForValue();
//			Object v = cache.get(key);
//			if(v != null) {
//				try {
//					response.getWriter().print(v.toString());
//				} catch (IOException e) {
//					logger.error("",e);
//				}
//			}
//		}
//	}
	
//	@RequestMapping("/setRedisValue")
//	@ResponseBody
//	public void setRedisValue(HttpServletRequest request, HttpServletResponse response, Model model) {
//		String key = request.getParameter("key");
//		String value = request.getParameter("value");
//		String along = request.getParameter("long");
//		ValueOperations<String, String> cache = redisTemplate.opsForValue();
//		if(StringUtil.isNotBlank(along)) {
//			cache.set(key, value, Long.valueOf(along), TimeUnit.SECONDS);
//		} else {
//			cache.set(key, value);
//		}
//	}
	
//	@RequestMapping("/removeRedisValue")
//	@ResponseBody
//	public void removeRedisValue(HttpServletRequest request, HttpServletResponse response, Model model) {
//		String key = request.getParameter("key");
//		ValueOperations<String, String> cache = redisTemplate.opsForValue();
//		cache.set(key, "", 1, TimeUnit.SECONDS);
//	}
	
//	@RequestMapping("/getProp")
//	@ResponseBody
//	public void getProp(HttpServletRequest request, HttpServletResponse response, Model model) {
//		String key = request.getParameter("key");
//		try {
//			response.getWriter().print(ConfKit.get(key));
//		} catch (IOException e) {
//			logger.error("",e);
//		}
//	}
	
//	@RequestMapping("/getSignature")
//	public HttpEntity<String> getSignature(HttpServletRequest request, Model model,@RequestBody String url) {
//		JSONObject json = new JSONObject();
//		try {
//			url = URLDecoder.decode(url,"UTF-8");
//			String jsapiTicket = redisTemplate.opsForValue().get(CacheConstants.WECHAT_TICKET);
//			Map<String, String> datas = WeChat.jsApiSign(jsapiTicket, url);
//			json = JSONObject.fromObject(datas);
//			json.put("code", "1");
//			json.put("message", "获取签名成功！");
//			return new ResponseEntity<String>(json.toString(),HttpStatus.OK);
//		} catch (Exception e) {
//			logger.error(e);
//			json.put("code", "-1");
//			json.put("message", "获取签名系统错误");
//			return new ResponseEntity<String>(json.toString(),HttpStatus.INTERNAL_SERVER_ERROR);
//		}	
//	}
	
	@RequestMapping("/createMenu")
	@ResponseBody
	public String createMenu(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		
		ValueOperations<String, String> cache = redisTemplate.opsForValue();
		String accessToken = (String) cache.get(WebContext.WECHAT_ACCESS_TOKEN);
		try {
			
			JSONObject butobj = new JSONObject();
			
			
			JSONArray buttons = new JSONArray();
			
			//按钮一/./
			JSONObject button1 = new JSONObject();
			button1.put("type", "miniprogram");
			button1.put("name", "我要用章");
			button1.put("url", "http://gzws-yl.com/#/user");
			button1.put("appid", "wx686d9ffcb83af55e");
			button1.put("pagepath", "pages/index/index");
			buttons.add(button1);
			
			
			JSONObject button2 = new JSONObject();
			button2.put("type", "view");
			button2.put("name", "公司官网");
			button2.put("url", "http://www.gzws-qd.com/");
			buttons.add(button2);
			
			
			
			
//			//菜单二
//			JSONArray button2subs = new JSONArray();
//			
//			JSONObject sub1 = new JSONObject();
//			sub1.put("type", "click");
//			sub1.put("name", "产品介绍");
//			sub1.put("key", "whqLuUUgimO9FF2cc0Kg-iwAlulu6KuELE4IAGTJbvM");
//			button2subs.add(sub1);
//			
//			JSONObject sub2 = new JSONObject();
//			sub2.put("type", "view");
//			sub2.put("name", "加盟代理");
//			sub2.put("url", "http://pcbd.7158.cn/7158/0496768/2_0_0_w.html");
//			button2subs.add(sub2);
//			
//			JSONObject sub3 = new JSONObject();
//			sub3.put("type", "view");
//			sub3.put("name", "相关视频");
//			sub3.put("url", "http://mp.weixin.qq.com/s?__biz=MzU3NTIxOTUxMg==&mid=100000002&idx=1&sn=9e6dbe068d8093292917f07f04770a1b&chksm=7d2733554a50ba43bc1e421097d804355035e52138ae182fd5682ed0a46f5e55258547eec7c0&scene=18#wechat_redirect");
//			button2subs.add(sub3);
//			
//			JSONObject sub4 = new JSONObject();
//			sub4.put("type", "view");
//			sub4.put("name", "操作指南");
//			sub4.put("url", "http://gzws-yl.com/#/guide");
//			button2subs.add(sub4);
//			
//			
//			JSONObject button2 = new JSONObject();
//			button2.put("name", "产品资讯");
//			button2.put("sub_button", button2subs);
//			buttons.add(button2);
//			
//			
//			//按钮三
//			JSONArray button3subs = new JSONArray();
//			
//			JSONObject bt3sub1 = new JSONObject();
//			bt3sub1.put("type", "view");
//			bt3sub1.put("name", "公司官网");
//			bt3sub1.put("url", "http://www.gzws-rcz.cn/");
//			button3subs.add(bt3sub1);
//			
//			JSONObject bt3sub2 = new JSONObject();
//			bt3sub2.put("type", "click");
//			bt3sub2.put("name", "联系我们");
//			bt3sub2.put("key", "whqLuUUgimO9FF2cc0Kg-hOGwmbdbWqvVnSoS0LBdiU");
//			button3subs.add(bt3sub2);
//			
//			JSONObject bt3sub3 = new JSONObject();
//			bt3sub3.put("type", "click");
//			bt3sub3.put("name", "招商实录");
//			bt3sub3.put("key", "whqLuUUgimO9FF2cc0Kg-iUR1r5g1pCHRdbaj3V_vb4");
//			button3subs.add(bt3sub3);
//			
//			
//			JSONObject button3 = new JSONObject();
//			button3.put("name", "关于我们");
//			button3.put("sub_button", button3subs);
//			buttons.add(button3);
			
			butobj.put("button", buttons);
			
			System.out.println(butobj.toString());
			WeChat.menu.createMenu(accessToken, butobj.toString());
			
		} catch (Exception e) {
			logger.error("",e);
			
			return "error";
		}
		
		
		return "ok";
	}
	
	@RequestMapping("/sendTextMsg")
	@ResponseBody
	public void sendTextMsg(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		
		
	}
	
//	@RequestMapping("/sendTextMsg")
//	@ResponseBody
//	public void sendTextMsg(HttpServletRequest request, HttpServletResponse response, Model model) {
//		String openId = request.getParameter("openId");
//		String content = request.getParameter("content");
//		ValueOperations<String, String> cache = redisTemplate.opsForValue();
//		String accesToken = (String) cache.get(CacheConstants.WECHAT_ACCESS_TOKEN);
//		try {
//			Message.sendText(accesToken, openId, content);
//			response.getWriter().print("SUCCESS");
//		} catch (Exception e) {
//			logger.error("",e);
//			try {
//				response.getWriter().print("ERROR");
//			} catch (IOException e1) {
//				e1.printStackTrace();
//			}
//		}
//	}
	
	public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, UnsupportedEncodingException, IOException, ExecutionException, InterruptedException {
		
//		String token = "16_kC7x_EadO-QQkkIzuMcZvYmM-HqE0OfAOrRettBPRPEqF652X6N5w9v9H43iYMbpp2TYhLJUrM4__F_qAk4TZasYBGQhjwGW197SPqedmphSMz7M4mNp1D6uMSbn3CFuyNOFSX0A1Gij-bAyNWVgABAAJI";
//		
//		JSONObject params = new JSONObject();
//		params.put("type", "news");
//		params.put("offset", "0");
//		params.put("count", "20");
//		String a = HttpKit.post("https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+token,params.toString());
//		System.out.println(a);
		
		
		
		
//		
//		System.out.println(buttons.toString());
		
		
		
		
		JSONArray touser = new JSONArray();
		touser.add("OPENID1");
		
		JSONObject mpnews = new JSONObject();
		mpnews.put("media_id", "123dsdajkasd231jhksad");
		
		JSONObject obj = new JSONObject();
		obj.put("touser", touser);
		obj.put("mpnews", mpnews);
		obj.put("msgtype", "mpnews");
		obj.put("send_ignore_reprint", 0);
		System.out.println(obj.toString());
		
//		{
//			   "touser":[
//			    "OPENID1",
//			    "OPENID2"
//			   ],
//			   "mpnews":{
//			      "media_id":"123dsdajkasd231jhksad"
//			   },
//			    "msgtype":"mpnews"，
//			    "send_ignore_reprint":0
//			}
		
		
		
		
	}
	
	
}
